/*
 * @Author: wuzhouhai wzh200x@126.com
 * @Date: 2024-04-12 16:02:54
 * @LastEditors: wuzhouhai wzh200x@126.com
 * @LastEditTime: 2024-07-12 15:38:39
 * @FilePath: \dwys_web\extensions\phoenix-plugin-client\assets\core\net\message\header.ts
 * @Description: 
 */
import ByteBuffer from "bytebuffer/dist/bytebuffer.min.js";


export class MessageHeader {
    public static HEADER_LENGTH: number = 16;  // 消息头部长度
    public Length: number = 0;     // 包长度
    public VerifyID: number = 0;   // 验证ID 只增不减少
    public Opcode:number = 0;      // 消息码
    public OpcodeType:number = 4;  // 消息码类型,决定解包
    public Masked:boolean = false; // 是否有掩码
    public Mask:Uint8Array = new Uint8Array(4);   // 掩码


    public reset(){
        this.Length = 0;
        this.VerifyID = 0;
        this.Opcode = 0;
        this.OpcodeType = 4;
        this.Masked = false;
        this.Mask = new Uint8Array(4);
    }

    public decode(data: Uint8Array) {
        if(data.length < 16) {
            return;
        }
        //@ts-ignore
        let dataBuf = ByteBuffer.wrap(data);
        this.Length = dataBuf.readInt32();
        this.VerifyID = dataBuf.readUint32();
        this.Opcode = dataBuf.readUint16();
        this.OpcodeType = dataBuf.readUint8();
        this.Masked = dataBuf.readUint8() == 1;
        for (let i = 0; i < 4; i++) {
            this.Mask[i] = dataBuf.readUint8();
        }
    }

    public encode(): Uint8Array{
        //@ts-ignore
        let dataBuf = ByteBuffer.allocate(16);
        dataBuf.writeInt32(this.Length);
        dataBuf.writeUint32(this.VerifyID);
        dataBuf.writeUint16(this.Opcode);
        dataBuf.writeUint8(this.OpcodeType);
        dataBuf.writeUint8(this.Masked? 1:0);
        for (let i = 0; i <4; i++) {
            dataBuf.writeUint8(this.Mask[i]);
        }
        dataBuf.flip();
        return new Uint8Array(dataBuf.toBuffer());
    }
}